import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'ai_chat_controller.dart';
import '../../function/model/ai_chat_message_model.dart';
import '../../function/utils/my_common.dart';
import '../../function/widgets/report_dialog.dart';

/// AI聊天页面
class AiChatPage extends GetView<AiChatController> {
  const AiChatPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/ai_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Column(
          children: [
            // 顶部导航栏
            _buildTopBar(),

            SizedBox(height: 120.h),

            // 消息容器区域
            Expanded(child: _buildMessageContainer()),
          ],
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(Get.context!).padding.top,
        left: 16.w,
        right: 16.w,
        bottom: 16.h,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Get.back(),
            child: Icon(
              Icons.arrow_back_ios_new,
              size: 20.sp,
              color: MyCommonUtils.white,
            ),
          ),

          // 标题
          Text(
            'AI Chat',
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.w700,
              color: MyCommonUtils.white,
              fontFamily:
                  GoogleFonts.berkshireSwash(
                    fontWeight: FontWeight.w700,
                  ).fontFamily,
            ),
          ),

          // 举报按钮
          GestureDetector(
            onTap: () {
              ReportDialogUtils.showReportDialog(
                onReportSubmitted: (reportType) {
                  // 举报成功后删除所有对话消息并返回上一页
                  controller.clearAllMessages();
                  Get.back();
                },
              );
            },
            child: Image.asset(
              'assets/images/report.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息容器
  Widget _buildMessageContainer() {
    return Container(
      decoration: BoxDecoration(
        image: const DecorationImage(
          image: AssetImage('assets/images/ai_message_container.png'),
          fit: BoxFit.fill,
        ),
      ),
      padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 16.h),

      child: Column(
        children: [
          // 消息列表区域
          Expanded(child: _buildMessageList()),

          // 输入框区域
          _buildInputArea(),
        ],
      ),
    );
  }

  /// 构建消息列表
  Widget _buildMessageList() {
    return GetX<AiChatController>(
      builder: (controller) {
        final messages = controller.aiChatState.allMessages;

        if (messages.isEmpty) {
          return Center(
            child: Text(
              'Start a conversation with AI',
              style: TextStyle(fontSize: 16.sp, color: Colors.grey[600]),
            ),
          );
        }

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          itemCount: messages.length,
          itemBuilder: (context, index) {
            final message = messages[index];
            return _buildMessageItem(message);
          },
        );
      },
    );
  }

  /// 构建单个消息项
  Widget _buildMessageItem(AiChatMessageModel message) {
    final isUser = message.messageType == AiMessageType.user;

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        mainAxisAlignment:
            isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isUser) ...[
            // AI头像
            CircleAvatar(
              radius: 20.w,
              backgroundImage: const AssetImage('assets/images/ai_avatar.png'),
            ),
            SizedBox(width: 12.w),
          ],

          // 消息内容
          Flexible(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color:
                    isUser
                        ? MyCommonUtils.blue.withValues(alpha: 0.9)
                        : Colors.white.withValues(alpha: 0.9),
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    message.content,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: isUser ? MyCommonUtils.white : Colors.black87,
                      height: 1.4,
                    ),
                  ),

                  if ((message.isSending || message.isFailed) && !isUser) ...[
                    SizedBox(height: 8.h),
                    _buildMessageStatus(message),
                  ],
                ],
              ),
            ),
          ),

          if (isUser) ...[
            SizedBox(width: 12.w),
            // 用户头像
            CircleAvatar(
              radius: 20.w,
              backgroundImage:
                  controller.getUserAvatar().isNotEmpty
                      ? AssetImage(controller.getUserAvatar())
                      : null,
              child:
                  controller.getUserAvatar().isEmpty
                      ? Icon(
                        Icons.person,
                        size: 24.sp,
                        color: MyCommonUtils.white,
                      )
                      : null,
            ),
          ],
        ],
      ),
    );
  }

  /// 构建消息状态
  Widget _buildMessageStatus(AiChatMessageModel message) {
    if (message.isSending) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 12.w,
            height: 12.w,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(
                message.messageType == AiMessageType.user
                    ? MyCommonUtils.white
                    : MyCommonUtils.blue,
              ),
            ),
          ),
          SizedBox(width: 8.w),
          Text(
            message.content == 'thinking...' ? 'Thinking...' : 'Sending...',
            style: TextStyle(
              fontSize: 12.sp,
              color:
                  message.messageType == AiMessageType.user
                      ? MyCommonUtils.white.withValues(alpha: 0.7)
                      : Colors.grey[600],
            ),
          ),
        ],
      );
    } else if (message.isFailed) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.error_outline, size: 16.sp, color: MyCommonUtils.pink),
          SizedBox(width: 8.w),
          GestureDetector(
            onTap: () => controller.resendMessage(message.id),
            child: Text(
              'Tap to retry',
              style: TextStyle(
                fontSize: 12.sp,
                color: MyCommonUtils.pink,
                decoration: TextDecoration.underline,
              ),
            ),
          ),
        ],
      );
    }

    return const SizedBox.shrink();
  }

  /// 构建输入区域
  Widget _buildInputArea() {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: GetX<AiChatController>(
        builder: (controller) {
          return Container(
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Row(
              children: [
                // 输入框
                Expanded(
                  child: TextField(
                    controller: controller.messageController,
                    focusNode: controller.messageFocusNode,
                    decoration: InputDecoration(
                      hintText: 'Type a message...',
                      hintStyle: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[500],
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                    ),
                    maxLines: null,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => controller.sendMessage(),
                    enabled: !controller.isSending,
                  ),
                ),

                // 发送按钮（在输入框内部）
                Padding(
                  padding: EdgeInsets.only(right: 8.w),
                  child: GestureDetector(
                    onTap: controller.sendMessage,
                    child: Image.asset(
                      'assets/images/comment_send.png',
                      width: 32.w,
                      height: 32.w,
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
